import SparkMD5 from "spark-md5";
//  将文件名转化为hash+suffix值
export const fileName = (file) => new Promise((resolve,reject) => {
    let fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);
    fileReader.onload = () => {
        let spark = new SparkMD5.ArrayBuffer();   // 创建一个加密器
        spark.append(fileReader.result)
        let hash = spark.end();
        let suffix = /\.([a-zA-Z0-9]+$)/.exec(file.name)[1];    // 获取文件名后缀
        let hashName = hash+'.'+suffix;
        if (hashName){
            resolve(hashName);
        }else {
            reject('转化为hash地址失败');
        }
    }
})

//  切片 分为固定数量和固定大小
export function qieFile(file,hash,suffix) {
    let max = 1024 * 100;   // 分片固定大小为  100kB
    let count = 0;
    let chunks = [];
    let index = 0;
    if (file.size >= 1024 * 1000){   //  文件大于1000kB就开始分片
        count = Math.ceil(file.size / max);
        if (count > 100) {
            max = file.size / 100;   // 分为100片
            count = 100;
        }
        while(index < count) {
            chunks.push({
                file: file.slice(index * max, (index+1) * max),
                filename: `${hash}_${index+1}.${suffix}`,
                count: count
            })
            index++;
        }
    }
    return chunks;
}

// 获得hash值
export const hash = (file) => new Promise((resolve,reject) => {
    let fileReader = new FileReader();
    fileReader.readAsArrayBuffer(file);
    fileReader.onload = () => {
        let spark = new SparkMD5.ArrayBuffer();   // 创建一个加密器
        spark.append(fileReader.result)
        let hash = spark.end()
        if (hash){
            resolve(hash);
        }else {
            reject('转化为hash失败');
        }
    }
})

// 获得后缀名
export function suffix(file) {
        // 获取文件名后缀
    return /\.([a-zA-Z0-9]+$)/.exec(file.name)[1];
}

export function sum() {

}




















